package com.myrslok.set;

import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

public class DeleteFileAction implements ResourceSet.ResourceAction<File> {

    private static final Logger logger = LoggerFactory.getLogger(DeleteFileAction.class);

    private static final DeleteFileAction instance = new DeleteFileAction();

    public static DeleteFileAction getInstance() {
        return instance;
    }

    private boolean ignoreErrors = false;
    private boolean verbose = false;

    @Override
    public void run(@NotNull final File file) {
        if (file.exists()) {
            deleteTree(file);
        } else {
            if (!ignoreErrors) {
                throw new RuntimeException(file + " does not exist");
            }
        }
    }

    private void deleteTree(@NotNull final File file) {
        if (file.isDirectory()) {
            for (final File f : file.listFiles()) {
                if (f.isFile()) {
                    delete(f);
                } else if (f.isDirectory()) {
                    deleteTree(f);
                }
            }
        }
        delete(file);
    }

    private void delete(@NotNull final File file) {
        if (verbose) {
            logger.info("Deleting " + file);
        }
        if (!file.delete() && !ignoreErrors) {
            logger.error("Could not delete {}", file);
            throw new RuntimeException("Could not delete " + file);
        }
    }

    public DeleteFileAction setIgnoreErrors(final boolean ignoreErrors) {
        this.ignoreErrors = ignoreErrors;
        return this;
    }

    public DeleteFileAction setVerbose(final boolean verbose) {
        this.verbose = verbose;
        return this;
    }
}
